<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}

			#box {
				height: 800px;
				margin: 50px auto;
				border: 2px solid black;
				position: relative;
			}

			#box>div {
				position: absolute;
				text-align: center;
				border-radius: 50%;
			}

		</style>
	</head>
	<body>
		请输入小球的数量<input type="number" id="number">
		<button id="create">创建小球</button>
		R: <input type="number" id="red">
		G: <input type="number" id="green">
		B: <input type="number" id="blue">
		<button id="change">改变颜色</button>
		<div id="box"></div>
		
	</body>
</html>
<script>
	// 获取元素 
	var createBtn = document.getElementById('create');

	var numberInput = document.getElementById('number');

	var boxDiv = document.getElementById('box');

	var changeBtn = document.getElementById('change');

	// 点击的小球	
	var curBall = null;

	// 添加点击事件
	createBtn.onclick = function() {
		// 清空box中的div
		boxDiv.innerHTML = "";
		var number = numberInput.value;
		for (var i = 0; i < number; i++) {
			var div = document.createElement('div');
			var width = randomNumber(100, 200);
			// 宽度
			div.style.width = width + 'px';
			// 高度
			div.style.height = div.style.width;
			// 行高
			div.style.lineHeight = div.style.height;
			// 字体大小
			div.style.fontSize = width / 2 + 'px';

			// left
			div.style.left = randomNumber(0, boxDiv.clientWidth - width) + 'px';
			// top
			div.style.top = randomNumber(0, boxDiv.clientHeight - width) + 'px';

			div.style.background = randomColor();

			div.innerHTML = i;
			div.onclick = function() {
				curBall = this;
			};

			boxDiv.appendChild(div);
		}

	};

	// 改变点击的小球的颜色
	changeBtn.onclick = function() {

		if (!curBall) return;
		var r = document.getElementById('red').value ? document.getElementById('red').value : 0;
		var g = document.getElementById('green').value ? document.getElementById('green').value : 0;
		var b = document.getElementById('blue').value ? document.getElementById('blue').value : 0;

		curBall.style.background = "rgb(" + r + "," + g + "," + b + ")";
		console.log("rgb(" + r + "," + g + "," + b + ")");

	};

	// 键盘事件
	document.onkeydown = function(e)  {
		if (!curBall) return;

		var l = curBall.offsetLeft;
		var t = curBall.offsetTop;

		if (e.keyCode == 38) {
			t -= 5;
		} else if (e.keyCode == 40) {
			t += 5;
		} else if (e.keyCode == 37) {
			l -= 5;
		} else if (e.keyCode == 39) {
			l += 5;
		}

		curBall.style.left = l + 'px';
		curBall.style.top = t + 'px';

 	};


	function randomNumber(m, n) {
		return Math.floor(Math.random() * (n - m + 1) + m);
	}

	function randomColor() {
		var r = randomNumber(0, 255);
		var g = randomNumber(0, 255);
		var b = randomNumber(0, 255);
		return "rgb(" + r + "," + g + "," + b + ")"; 
	}



	







</script>